from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models import MoodRecord, db
from datetime import date

mood_bp = Blueprint('mood', __name__)

@mood_bp.route('/api/mood', methods=['POST'])
@jwt_required()
def create_mood_record():
    user_id = get_jwt_identity()
    data = request.json
    
    # 校验情绪分类结构
    emotion = data.get('emotion')
    if not isinstance(emotion, dict) or 'category' not in emotion:
        return jsonify(code=400, msg='无效的情绪分类'), 400
    
    # 创建记录
    new_record = MoodRecord(
        user_id=user_id,
        emotion=emotion,
        details=data.get('details', ''),
        image_urls=data.get('image_urls', []),
        date=data.get('date', date.today().isoformat())
    )
    db.session.add(new_record)
    db.session.commit()
    
    return jsonify(code=200, data={'id': new_record.id})

@mood_bp.route('/api/mood', methods=['GET'])
@jwt_required()
def get_mood_history():
    user_id = get_jwt_identity()
    page = request.args.get('page', 1, type=int)
    per_page = 15
    
    records = MoodRecord.query.filter_by(user_id=user_id)\
        .order_by(MoodRecord.date.desc())\
        .paginate(page=page, per_page=per_page)
    
    return jsonify({
        'data': [{
            'id': r.id,
            'date': r.date.isoformat(),
            'emotion': r.emotion,
            'preview': r.details[:50] + '...' if r.details else ''
        } for r in records.items],
        'total_pages': records.pages
    })